package com.springJdbc;

import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl /* extends JdbcDaoSupport */ implements UserDao{
	
	 @Autowired 
	//通过注入实现JdbcTemplate的实例化
	private JdbcTemplate jdbcTemplate;

	public int addUser(User user) {
		String sql = "insert into user values(null,?,?)";
		//参数可以封装到object数组中，也可以直接传递
		Object[] objects = new Object[]{user.getUsername(),user.getPassword()};
		//int update = jdbcTemplate.update(sql,objects);
		int i = jdbcTemplate.update(sql, user.getUsername(),user.getPassword());
		return i;
	}

	public int delectU(User user) {
		int id = user.getId();
		String sql = "delete from user where id = ?";
		int i = jdbcTemplate.update(sql, id);
		return i;
	}

	//通过id查询与queryForObject不同在于可以查询为空，queryForObject查询为空时会报错
	public List<User> selectOne(int id) {
		String sql = "select * from user where id = ?";
		RowMapper<User> rowMapper =  new BeanPropertyRowMapper<User>(User.class);
		Object[] objects = new Object[]{id};
		java.util.List<User> list = jdbcTemplate.query(sql,objects,rowMapper);
		return list;
	}
	//查询全部
	public List<User> selectAll() {
		String sql = "select * from user";
		RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
		//List<User> list = this.getJdbcTemplate().query(sql, rowMapper);
		List<User> list = jdbcTemplate.query(sql, rowMapper);
		return list;
	}
	//通过id查询
	public User select(int id) {
		String sql = "select * from user where id = ?";
		RowMapper<User> rowMapper 
			=  new BeanPropertyRowMapper<User>(User.class);
		User user = jdbcTemplate.queryForObject(sql, rowMapper,id);
		return user;
	}
	
	
	
	

}
